<template>
  <div ref="itemRef" :style="outerStyle" :class="cls" @click="onClick">
    <span ref="wrapperRef" :style="wrapperStyle" :class="wrapperCls">
      <template v-if="isImage">
        <slot v-if="hasError" name="error">
          <div :class="`${prefixCls}-image-icon`">
            <a-icon name="tupiancuowu"></a-icon>
          </div>
        </slot>
        <slot v-if="!(hasError || !shouldLoad) && !isLoaded">
          <div :class="`${prefixCls}-image-icon`">
            <!-- <IconLoading /> -->
          </div>
        </slot>
        <image
          v-if="!(hasError || !shouldLoad)"
          :src="imageUrl"
          :style="{
            width: size + 'px',
            height: size + 'px',
            objectFit: objectFit,
          }"
          alt="avatar"
          @load="handleImgLoad"
          @error="handleImgError"
        />
      </template>
      <slot v-else>{{ title }}</slot>
    </span>
    <!-- <div
      v-if="$slots['trigger-icon']"
      :class="`${prefixCls}-trigger-icon-${triggerType}`"
      :style="computedTriggerIconStyle"
    >
      <slot name="trigger-icon" />
    </div> -->
  </div>
</template>

<script lang="ts">
import {
  computed,
  CSSProperties,
  defineComponent,
  nextTick,
  onMounted,
  ref,
  toRefs,
  watch,
} from "vue";
import { props } from "./props";
import { isNumber } from "@/utils/is";
import { useElementSize } from "@/ArcoUni/hook/user-size-dom";

export default defineComponent({
  name: "Avatar",
  options: {
    // 虚拟化节点
    virtualHost: true,
  },
  props,
  emits: ["click", "error", "load"],
  setup(props, { slots, emit }) {
    const { shape, size, autoFixFontSize } = toRefs(props);

    // const groupCtx = inject(avatarGroupInjectionKey, undefined);
    const groupCtx = undefined;
    const prefixCls = "arco-avatar";

    const mergedShape = computed(() => groupCtx?.shape ?? shape.value);
    const mergedSize = computed(() => groupCtx?.size ?? size.value);
    const mergedAutoFixFontSize = computed(
      () => groupCtx?.autoFixFontSize ?? autoFixFontSize.value,
    );

    const isImage = computed(() => props.imageUrl);

    const { getSelectorQuery } = useElementSize(".arco-avatar-wrapper");
    const { getSelectorQuery: getSelectorQuerys } =
      useElementSize(".arco-avatar");
    // const isImage = ref(false);
    const hasError = ref(false);
    const isLoaded = ref(false);
    const shouldLoad = ref(true);
    const index = ref(-1);

    const onClick = (e: MouseEvent) => {
      emit("click", e);
    };

    const handleImgLoad = () => {
      isLoaded.value = true;
      emit("load");
    };

    const handleImgError = () => {
      hasError.value = true;
      emit("error");
    };

    const outerStyle = computed(() => {
      const style: CSSProperties = isNumber(mergedSize.value)
        ? {
            width: `${mergedSize.value}px`,
            height: `${mergedSize.value}px`,
            fontSize: `${mergedSize.value / 2}px`,
          }
        : {};
      if (groupCtx) {
        style.zIndex = groupCtx.zIndexAscend
          ? index.value + 1
          : groupCtx.total - index.value;
        style.marginLeft =
          index.value !== 0 ? `-${(mergedSize.value ?? 40) / 4}px` : "0";
      }
      return style;
    });

    // isImage.value || props.imageUrl
    const wrapperCls = computed(() => [
      `${prefixCls}-wrapper`,
      props.imageUrl ? `${prefixCls}-image` : `${prefixCls}-text`,
    ]);

    const cls = computed(() => [
      prefixCls,
      `${prefixCls}-${mergedShape.value}`,
      {
        [`${prefixCls}-with-trigger-icon`]: Boolean(slots["trigger-icon"]),
      },
    ]);

    const wrapperStyle = ref({});

    const autoFixFontSizeHandler = async () => {
      wrapperStyle.value = {};
      if (!props.imageUrl) {
        nextTick(async () => {
          const textWidth = await getSelectorQuery();
          const avatarWidth = await getSelectorQuerys();
          const scale = avatarWidth.width / (textWidth.width + 8);
          let transFoms = {};
          if (avatarWidth && scale < 1) {
            transFoms["transform"] = `scale(${scale}) translateX(-50%)`;
          }
          wrapperStyle.value = transFoms;
        });
      }
    };

    watch(
      () => props.title,
      () => {
        autoFixFontSizeHandler();
      },
    );

    onMounted(() => {
      if (mergedAutoFixFontSize.value) {
        autoFixFontSizeHandler();
      }
    });

    return {
      prefixCls,
      cls,
      outerStyle,
      wrapperCls,
      isLoaded,
      hasError,
      shouldLoad,
      wrapperStyle,
      onClick,
      handleImgLoad,
      handleImgError,
      isImage,
    };
  },
});
</script>
